const mongoose = require('mongoose')
const Movie = mongoose.model('movie')
const { formatBody } = require('../tools')

module.exports = {
  /**
   * 获取电影列表
   */
  async list (ctx) {
    let page = ctx.query.page || 1
    let pageSize = ctx.query.pageSize || 20
    let type = ctx.query.type || ''
    let keyword = ctx.query.keyword || ''
    let movies
    if (keyword) {
      movies = await Movie.find({
        $or: [
          { type: '' },
          { title: { $regex: keyword, $options: '$i' } }
        ]
      })
      .sort({ 'meta.createdAt': -1 })
      .limit(+pageSize).skip(+pageSize * (+page - 1))
    } else {
      movies = await Movie.find({
        type: type + ''
      })
      .sort({ 'meta.createdAt': -1 })
      .limit(+pageSize).skip(+pageSize * (+page - 1))
    }
    return ctx.body = formatBody(1, 'ok', movies)
  },
  /**
   * 删除所有电影
   */
  async clearAll (ctx) {
    await Movie.remove()
    return ctx.body = formatBody(1, '删除成功', {})
  },
  /**
   * 删除一部电影
   */
  async delete (ctx) {
    const movie = await Movie.find({
      id: ctx.query.id
    })
    if (movie.length > 0) {
      await Movie.deleteOne({ id: ctx.query.id })
      return ctx.body = formatBody(1, 'ok', movie)
    }
    return ctx.body = formatBody(0, '不存在该记录，无法进行删除操作')
  },
  /**
   * 更新电影信息
   */
  async update (ctx) {
    let query = ctx.query
    const movie = await Movie.find({ id: query.id })
    if (movie.length > 0) {
      const title = query.title || movie[0].title
      const poster = query.poster || movie[0].poster
      await Movie.update({
        id: query.id
      }, {
        title, poster
      })
      return ctx.body = formatBody(1, '更新成功')
    }
    return ctx.body = formatBody(1, '不存在该记录，无法进行更新操作')
  }
}
